package com.example.bledemo.ui;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.bledemo.MainActivity;
import com.example.bledemo.R;
import com.example.bledemo.ui.BaseActivity;
import com.example.bledemo.util.IpSettingsManager;
import com.example.bledemo.util.NetworkUtils;

import java.util.regex.Pattern;

public class IpSettingsActivity extends BaseActivity {

    private static final String TAG = "IpSettingsActivity";
    
    private EditText etIpAddress;
    private EditText etPort;
    private Button btnConfirm;
    private ProgressDialog progressDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_ip_settings;
    }

    @Override
    protected void initViews() {
        etIpAddress = findViewById(R.id.et_ip_address);
        etPort = findViewById(R.id.et_port);
        btnConfirm = findViewById(R.id.btn_confirm);
        
        btnConfirm.setOnClickListener(v -> validateAndConnect());
    }

    @Override
    protected void initData() {
        loadSavedSettings();
    }

    /**
     * 加载保存的设置
     */
    private void loadSavedSettings() {
        String savedIp = IpSettingsManager.getIpAddress(this);
        int savedPort = IpSettingsManager.getPort(this);
        
        if (!TextUtils.isEmpty(savedIp)) {
            etIpAddress.setText(savedIp);
        }
        
        if (savedPort > 0) {
            etPort.setText(String.valueOf(savedPort));
        }
    }

    /**
     * 验证输入并连接
     */
    private void validateAndConnect() {
        String ipAddress = etIpAddress.getText().toString().trim();
        String portStr = etPort.getText().toString().trim();
        
        // 验证IP地址格式
        if (TextUtils.isEmpty(ipAddress)) {
            showToast("请输入IP地址");
            etIpAddress.requestFocus();
            return;
        }
        
        if (!isValidIpAddress(ipAddress)) {
            showToast("IP地址格式不正确");
            etIpAddress.requestFocus();
            return;
        }
        
        // 验证端口号
        if (TextUtils.isEmpty(portStr)) {
            showToast("请输入端口号");
            etPort.requestFocus();
            return;
        }
        
        int port;
        try {
            port = Integer.parseInt(portStr);
        } catch (NumberFormatException e) {
            showToast("端口号必须是数字");
            etPort.requestFocus();
            return;
        }
        
        if (port < 1 || port > 65535) {
            showToast("端口号必须在1-65535之间");
            etPort.requestFocus();
            return;
        }
        
        // 保存设置
        saveSettings(ipAddress, port);
        
        // 显示连接对话框
        showConnectionDialog();
        
        // 开始连接测试
        new ConnectionTestTask().execute(ipAddress, String.valueOf(port));
    }

    /**
     * 验证IP地址格式
     */
    private boolean isValidIpAddress(String ipAddress) {
        String ipPattern = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
        return Pattern.matches(ipPattern, ipAddress);
    }

    /**
     * 保存设置
     */
    private void saveSettings(String ipAddress, int port) {
        IpSettingsManager.saveIpSettings(this, ipAddress, port);
    }

    /**
     * 显示连接对话框
     */
    private void showConnectionDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("连接测试");
        progressDialog.setMessage("正在测试连接...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    /**
     * 隐藏连接对话框
     */
    private void hideConnectionDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    /**
     * 异步连接测试任务
     */
    private class ConnectionTestTask extends AsyncTask<String, Void, NetworkUtils.ConnectionResult> {

        @Override
        protected NetworkUtils.ConnectionResult doInBackground(String... params) {
            String ipAddress = params[0];
            int port = Integer.parseInt(params[1]);
            
            return NetworkUtils.testTcpConnection(ipAddress, port);
        }

        @Override
        protected void onPostExecute(NetworkUtils.ConnectionResult result) {
            hideConnectionDialog();
            
            if (result.isSuccess()) {
                showToast("连接成功！");
                // 跳转到MainActivity
                startActivity(MainActivity.class);
                finish(); // 结束当前Activity
            } else {
                showToast("连接失败：" + result.getMessage());
            }
        }
    }
} 